package com.ebao.service.mail.impl;

import java.util.Arrays;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.ebao.constants.SystemSettingConstants;
import com.ebao.po.mail.TEmailRecord;
import com.ebao.service.common.ISettingService;
import com.ebao.service.mail.IMailService;
import com.ebao.service.mail.ITEmailRecordService;

/**
 * Class for sending e-mail messages based on Velocity templates or with
 * attachments.
 * 
 */
public class MailServiceImpl implements IMailService {
	
	private String defaultFrom;
	
	@Resource
	ITEmailRecordService emailRecordService;
	@Resource
	protected ISettingService settingService;

	/**
	 * Mail sender implementor.
	 */
	private MailSender mailSender;

	final Log log = LogFactory.getLog(MailServiceImpl.class);

	private VelocityEngine velocityEngine;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.xcesys.extras.webapp.service.IMailService#send(org.springframework
	 * .mail.SimpleMailMessage)
	 */
	@Override
	public void sendMessage(SimpleMailMessage msg) throws MailException {	
		try {
			mailSender.send(msg);
		} catch (MailException ex) {
			log.error(ex.getMessage());
			throw ex;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.xcesys.extras.webapp.service.IMailService#sendMessage(org.springframework
	 * .mail.SimpleMailMessage, java.lang.String, java.util.Map)
	 */
	@Override
	public void sendMessage(SimpleMailMessage msg, String templateName,
			Map<String, Object> model) {
		String result = null;

		try {
			result = VelocityEngineUtils.mergeTemplateIntoString(
					velocityEngine, templateName, model);
		} catch (VelocityException e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}

		msg.setText(result);
		sendMessage(msg);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.xcesys.extras.webapp.service.IMailService#sendMessage(java.lang.String
	 * [], java.lang.String, org.springframework.core.io.ClassPathResource,
	 * java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public void sendMessage(String[] recipients, String sender, String subject,
			String bodyText, ClassPathResource resource, String attachmentName)
			throws MessagingException {

		//记录邮件发送任务，以后由后台处理程序异步执行
		try {
			//recordEmail2Pool(recipients,sender,subject,bodyText,null,null);//目前没有支持附件
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		
		MimeMessage message = ((JavaMailSenderImpl) mailSender).createMimeMessage();

		// use the true flag to indicate you need a multipart message
		MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

		helper.setTo(recipients);

		// use the default sending if no sender specified
		if (sender == null) {
			helper.setFrom(defaultFrom);
		} else {
			helper.setFrom(sender);
		}

		helper.setText(bodyText, true);
		if (StringUtils.isBlank(subject)) {
			subject = "空主题";
		}
		helper.setSubject(subject);
		if (attachmentName != null && resource != null) {
			helper.addAttachment(attachmentName, resource);
		}
		if("1".equals(settingService.getValueByName(SystemSettingConstants.ENABLE_EMAIL_MODULE))){
			((JavaMailSenderImpl) mailSender).send(message);
		}
		
	}
 
	
	@Override
	public void sendMessage(String[] recipients, String sender, String subject,
			String templateName, Map<String, Object> model,
			ClassPathResource resource, String attachmentName)
			throws MessagingException {
		try {
			String bodyText = VelocityEngineUtils.mergeTemplateIntoString(
					velocityEngine, templateName, "UTF-8", model);
			sendMessage(recipients, sender, subject, bodyText, resource, attachmentName);
		} catch (VelocityException e) {
			log.error(e.getMessage());
		}
	}

	public void setFrom(String from) {
		this.defaultFrom = from;
	}

	public void setMailSender(MailSender mailSender) {
		this.mailSender = mailSender;
	}

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}
	
	public void recordEmail2Pool(String[] recipients, String from, String subject,
			String bodyText, ClassPathResource resource, String attachmentName){
		
	    log.debug("邮件记录开始$$$$$$$$$$$$$$$$$$");	

		TEmailRecord emailRecord = new TEmailRecord();
		
		if(from==null){
			emailRecord.setFrom("kf@shouhuobao.com");
		} else {
			emailRecord.setFrom(from);
		}
		
		//如果有多个接受者号码，则号码间以，分割
		if(recipients!=null) {
			String to = Arrays.toString(recipients);
			emailRecord.setTo(to.substring(1,to.length()));
		}
		
		emailRecord.setSubject(subject);
		emailRecord.setContent(bodyText);
		emailRecord.setAttachments(attachmentName);
		emailRecord.setHassend(Boolean.TRUE);//mask add  将保存的邮件设置为已发送
		emailRecordService.create(emailRecord);
	    log.debug("邮件记录成功$$$$$$$$$$$$$$$$$$");	
	}
}
